var Wei = {};

// form编辑器
Wei.FormEditor = Ext.extend(Ext.Panel, {
	
	formPath: null,		// 表单路径
	tbar_save: null,	// 工具栏上的save按钮
	tbar_preview: null,	// 工具栏上的preview按钮
	tbar_refresh: null, // 工具栏上的refresh按钮
	tbar_expand: null,	// 工具栏上的expand按钮
	tbar_path: null,	// 工具栏上的path
	panel_tree: null,
	panel_prop: null,
	editor_select: null,// 下拉编辑器
	
	closable: true,
	
	initComponent: function(){
		this.initTopbar();
		this.initFormTree();
		this.initPropPanel();
		this.layout = "border";
		this.items = [this.panel_tree, this.panel_prop];
		Wei.FormEditor.superclass.initComponent.call(this);
	},
	
	initTopbar: function(){
		this.tbar_save = new Ext.Button({
			text: "保存",
			icon: ctx+"/weifly/images/save.gif",
			handler: this.saveJsonForm,
			scope: this
		});
		this.tbar_preview = new Ext.Button({
			text: "预览",
			icon: ctx+"/weifly/images/preview.gif",
			handler: this.previewForm,
			scope: this
		});
		this.tbar_refresh = new Ext.Button({
			text: "刷新",
			icon: ctx+"/weifly/images/refresh.gif",
			handler: function(){
				this.loadFormJson();
			},
			scope: this
		});
		this.tbar_expand = new Ext.Button({
			text: "展开",
			icon: ctx+"/weifly/images/expandall.gif",
			handler: function(){
				this.panel_tree.root.expand(true);
			},
			scope: this
		});
		this.tbar_path = new Ext.Toolbar.TextItem({
			text: "<font color=red>"+this.formPath+"</font>"
		});
		this.tbar = [
			this.tbar_save,
			this.tbar_preview,
			this.tbar_refresh,
			this.tbar_expand,
			"->",
			this.tbar_path
		];
	},
	
	// 初始化节点树
	initFormTree: function(){
		this.panel_tree = new Ext.tree.TreePanel({
			region: "center",
			margins: "4 0 4 4",
			animate: false,
			enableDD: true,
			loader: new Ext.tree.TreeLoader({})
		});
		var root = new Ext.tree.TreeNode({
			text: "根节点",
			expanded: true
		});
		this.panel_tree.setRootNode(root);
		this.panel_tree.on("contextmenu", this.treeMenuHandler, this);
		this.panel_tree.on("click", this.treeNodeClick, this);
		this.panel_tree.on("beforenodedrop", this.dragNodeHander, this);
		this.panel_tree.on("nodedragover", this.dragoverHandler, this);
	},
	
	dragNodeHander: function(e){
		var t = e.target;
		var s = e.dropNode;
		if (e.point == "above"){
			t.parentNode.insertBefore(s, t);
		}else if(e.point == "append"){
			t.appendChild(s);
		}else if(e.point == "below"){
			if(t.nextSibling){
				t.parentNode.insertBefore(s, t.nextSibling);
			}else{
				t.appendChild(s);
			}
		}
		return true;
	},
	
	dragoverHandler: function(e){
		var t = e.target;
		var s = e.dropNode;
		if (t.getOwnerTree() != s.getOwnerTree()) {
			return false;
		}
		if(e.point=="above" || e.point=="below"){
			if(t.parentNode == s.parentNode){
				return true;
			}else{
				var pt = t.parentNode.attributes.jsonConf["type"];
				var ct = s.attributes.jsonConf["type"];
				return this.checkParentValid(pt, ct);
			}
		}else if(e.point=="append"){
			if(t==s.parentNode){
				return true;
			}else{
				var pt = t.attributes.jsonConf["type"];
				var ct = s.attributes.jsonConf["type"];
				return this.checkParentValid(pt, ct);
			}
		}
		return false;
	},
	
	// 加查是否可以有子类型控件
	checkParentValid: function(pt, ct){
		var child = metaJson[pt].child;
		if(child){
			for(var i=0;i<child.length;i++){
				if(child[i].type==ct){
					return true;
				}
			}
		}
		return false;
	},
	
	// 初始化属性列表
	initPropPanel: function(){
		var selCombo = new Ext.form.ComboBox({
			displayField: "name",
			valueField: "value",
			triggerAction: "all",
			typeAhead: true,
			editable: false,
			mode: "local",
			store: new Ext.data.ArrayStore({
				fields: ["name","value"]
			})
		});
		this.editor_select = new Ext.grid.GridEditor(selCombo);
		this.panel_prop = new Ext.grid.PropertyGrid({
			region: "east",
			split: true,
			margins: "4 4 4 0",
			width: 280
		});
		this.panel_prop.on("beforeedit", this.beforePropEdit, this);
		this.panel_prop.on("afteredit", this.afterPropEdit, this);
	},
	
	beforePropEdit: function(e){
		var propname = e.record.get("name");
		var pl = this.panel_prop.prop_list;
		var metaProp;
		for(var i=0;i<pl.length;i++){
			if(pl[i].name==propname){
				metaProp = pl[i];
			}
		}
		if(!metaProp){
			return ;
		}
		if(metaProp.type=="select" || metaProp.options){
			var od = metaProp.options.split(",");
			var data = [];
			for(var i=0;i<od.length;i++){
				data.push([od[i],od[i]]);
			}
			this.editor_select.field.store.loadData(data, false);
		}
	},
	
	afterPropEdit: function(){
		var node = this.panel_prop.tree_node;
		var nodeConf = node.attributes.jsonConf;
		var propList = metaJson[nodeConf.type].props;
		var propsSource = this.panel_prop.getSource();
		var propMap = {};
		for (var i = 0; i < propList.length; i++) {
			var propname = propList[i].name;
			if (propsSource[propname] != undefined) {
				var dv = String(propList[i].value);
				var nv = String(propsSource[propname]);
				if(nv != dv){
					propMap[propname] = nv;
				}
			}
		}
		nodeConf.props = propMap;
	},
	
	// 更新formPath
	updatePath: function(path, text){
		this.formPath = path;
		this.tbar_path.setText(path);
		this.setTitle(text);
	},
	
	afterRender: function(){
		Wei.FormEditor.superclass.afterRender.call(this);
		var me = this;
		(function(){
			me.loadFormJson();
		}).defer(30);
	},
	
	// 显示消息提示
	showUserMessage: function(str, type, hide){
		if(type){
			str = "<font color=red>"+str+"</font>";
		}
		this.el.mask(str);
		if(hide!==false){
			var me = this;
			(function(){
				me.el.unmask();
			}).defer(300);
		}
	},
	
	loadFormJson: function(){
		this.el.mask("加载中...");
		Ext.Ajax.request({
			url: "console?action=loadForm",
			scope: this,
			success: function(response){
				this.el.unmask();
				var nj = Ext.decode(response.responseText);
				var node = this.createTreeNode(nj);
				node.expanded = true;
				this.panel_tree.setRootNode(node);
				this.panel_tree.fireEvent("click", node);
			},
			params: {
				path: this.formPath
			}
		});
	},
	
	createTreeNode: function(nodeJson){
		var node = new Ext.tree.TreeNode({
			text: nodeJson.type,
			jsonConf: nodeJson
		});
		if(nodeJson.items){
			for(var i=0;i<nodeJson.items.length;i++){
				var sub = this.createTreeNode(nodeJson.items[i]);
				node.appendChild(sub);
			}
		}
		return node;
	},
	
	treeMenuHandler: function(node, e){
		node.select();
		var menu = fetchNodeMenu(node.attributes.jsonConf.type);
		menu.form_node = node;
		menu.form_editor = this;
		menu.showAt(e.getXY());
	},
	
	treeNodeClick: function(node, e){
		var type = node.attributes.jsonConf.type;
		var nodeProps = node.attributes.jsonConf.props;
		var propList = metaJson[type].props;
		var propMap = {};
		this.panel_prop.customEditors = {};
		for(var i=0;i<propList.length;i++){
			var propname = propList[i].name;
			var proptype = propList[i].type;
			if(nodeProps[propname]!==undefined){
				propMap[propname] = nodeProps[propname];
			}else{
				propMap[propname] = propList[i].value;
			}
			if(proptype=="number"){
				
			}else if(proptype=="boolean"){
				propMap[propname] = (propMap[propname]=="true");
			}else if(proptype=="select"){
				this.panel_prop.customEditors[propname] = this.editor_select;
			}
		}
		this.panel_prop.tree_node = node;
		this.panel_prop.prop_list = propList;
		this.panel_prop.setSource(propMap);
	},
	
	saveJsonForm: function(){
		var json = this.nodeToJson(this.panel_tree.root);
		var jsonStr = Ext.encode(json);
		this.el.mask("保存中...");
		Ext.Ajax.request({
			url: "console?action=saveForm",
			scope: this,
			success: function(response){
				if(response.responseText=="1"){
					this.showUserMessage("保存成功", true);
				}else{
					this.showUserMessage("错误："+response.responseText, true, false);
				}
			},
			params: {
				path: this.formPath,
				json: jsonStr
			}
		});
	},
	
	nodeToJson: function(node){
		var json = node.attributes.jsonConf;
		if(node.childNodes && node.childNodes.length>0){
			json.items = [];
			for(var i=0;i<node.childNodes.length;i++){
				var sub = this.nodeToJson(node.childNodes[i]);
				json.items.push(sub);
			}
		}else{
			delete json.items;
		}
		return json;
	},
	
	// 预览表单
	previewForm: function(){
		var url = ctx + "/parse" + this.formPath;
		var win = window.open(url, "weifly_preview");
		win.focus();
	},
	
	addItemNode: function(node, type){
		var sub = this.createTreeNode({
			type: type,
			props: {}
		});
		node.appendChild(sub);
		node.expand();
		sub.select();
		this.treeNodeClick(sub);
	},
	
	clearSubItem: function(node){
		node.removeAll(true);
	},
	
	delItemNode: function(node){
		node.remove(true);
	}
});